<?php

namespace common\model\sell66;

use common\db\Sell66;

class UserBalanceLog extends Sell66
{
    const type_withdrawals = 'withdraw'; // 提现

    // 设置当前模型对应的完整数据表名称
    protected $table = 'user_balance_log';
    protected $pk = 'user_balance_log_id';

    public static $sourceTypeText = [
        1 => '卖出收入',
        2 => '提现',
        3 => '消费',
        4 => '充值',
    ];
    
    public static $costType = [
    	'withdraw'
   	];
    public static $noteMaps = [
    	'robot_buy'=>'机器人购买',
    	'withdraw'=>'用户提现',
    	'commission'=>'佣金转移',
    ];
    
    public static $incomeType = [
    	'robot_buy',
        'commission',  //佣金算作收入类型，由佣金转移到账户
    ];
    
    public static $statusMaps = [
		    'init' => 1,
		    'success' => 2,
		    'failed' => 3,
    ];

    public static $statusText = [
        1 => '申请',
        2 => '成功',
        3 => '失败',
    ];

    public static function addUserBalanceLog($userId, $balanceId, $type, $sourceId, $money, $currentBalance, $budget = 2)
    {
        $record = UserBalanceLog::where(['user_id'=>$userId,'user_balance_id'=>$balanceId,'source_type'=>$type,'source_id'=>$sourceId])->count();

        if ($type != 'commission') {
            if($record > 0){
                return false;
            }
        }

        $userBalanceLogModel = new self ();
        $userBalanceLogModel->user_id = $userId;
        $userBalanceLogModel->user_balance_id = $balanceId;
        $userBalanceLogModel->source_type = $type;
        $userBalanceLogModel->source_id = $sourceId;
        $userBalanceLogModel->money = $money;
        $userBalanceLogModel->current_balance = $currentBalance;
        $userBalanceLogModel->balance_no = $userBalanceLogModel->createBlanceNo();

        if (self::type_withdrawals == $type) {
            $userBalanceLogModel->note = '用户提现';
        } else if($type == 'robot_buy') {
        	$userBalanceLogModel->status = self::$statusMaps['success'];
            $userBalanceLogModel->note = '机器人购买';
        }elseif($type == 'commission') {
        	$userBalanceLogModel->status = self::$statusMaps['success'];
            $userBalanceLogModel->note = '佣金转移钱包';
        }else{
        	$userBalanceLogModel->note = 'this is note';
        }

        $result = $userBalanceLogModel->save();
        if (!$result) {
            return false;
        }
        return $userBalanceLogModel->toArray();
    }

    private function createBlanceNo()
    {
        return str_pad(mt_rand(1, 99), 2, '0', STR_PAD_LEFT) . date('Ymd') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
    }
    
    public static function getIncomeMoney($userId){
    	$result =  UserBalanceLog::where(['user_id'=>$userId,'status'=>UserBalanceLog::$statusMaps['success']])
    	->where('source_type','in',UserBalanceLog::$incomeType)->sum('money');
    	if(empty($result)){
    		return 0;
    	}
    	return $result;
    }
    
    public static function getCostMoney($userId){
    	$result =  UserBalanceLog::where(['user_id'=>$userId])
    	->where('status' , 'in',[1,2])
    	->where('source_type','in',UserBalanceLog::$costType)->sum('money');
    	if(empty($result)){
    		return 0;
    	}
    	return $result;
    }

    /**
     * 获取用户账户记录数量
     * @param  int $userId 用户ID
     * @return int
     */
    public static function getBalanceLogNum($userId)
    {
        $where = array(
            'user_id' => $userId,
        );

        return static::where($where)->count();
    }

    /**
     * 获取用户佣金总金额
     * @param  int $userId 用户ID
     * @return int
     */
    public static function getProfitTotalAmount($userId)
    {
        $where = array(
            'user_id' => $userId,
            'source_type' => 'commission',
            'status' => UserBalanceLog::$statusMaps['success'],
        );

        return static::where($where)->sum('money');
    }
}